# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=openexr
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.1.5
pkgrel=2
pkgdesc='A high dynamic-range image file format library (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://www.openexr.com/"
license=('BSD')
depends=("${MINGW_PACKAGE_PREFIX}-imath"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread-git"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-ninja")
conflicts=(
  "${MINGW_PACKAGE_PREFIX}-ilmbase"
  "${MINGW_PACKAGE_PREFIX}-pyilmbase"
)
replaces=(
  "${MINGW_PACKAGE_PREFIX}-ilmbase"
  "${MINGW_PACKAGE_PREFIX}-pyilmbase"
)
source=("https://github.com/openexr/openexr/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        0001-mingw-w64-fix.patch
        0006-cmake-soversion.patch
        0009-win-dwalookups.patch)
sha256sums=('93925805c1fc4f8162b35f0ae109c4a75344e6decae5a240afdfce25f8a433ec'
            'b5ce04296e9711cace5c6a73ca13fc649b2fccde744023a6d2ff93dab23f7ba0'
            'e65852ac2e5545472ad90830c97e964aa2c71e1795979a8b9867155d578d45ed'
            'd7af93d993c5b09ff6be1f5198ab1239a95c550518ecc8de106f82c3d4185fbf')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Np1 -i "${srcdir}/$_patch"
  done
}

prepare(){
  cd "${srcdir}/${_realname}-${pkgver}"

  apply_patch_with_msg \
    0001-mingw-w64-fix.patch \
    0006-cmake-soversion.patch \
    0009-win-dwalookups.patch
}

build() {
  [[ -d "build-${MSYSTEM}" ]] && rm -rf "build-${MSYSTEM}"
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    extra_config+=("-DOPENEXR_BUILD_TOOLS=OFF")
  fi

  CXXFLAGS+=" -Wno-ignored-attributes"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      ${extra_config[@]} \
      -DBUILD_SHARED_LIBS=ON \
      -DBUILD_TESTING=OFF \
      -DOPENEXR_INSTALL_EXAMPLES=OFF \
      -DOPENEXR_INSTALL_PKG_CONFIG=ON \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE.md" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.md"
}
